<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>hibernate的基本用法 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="##  Hibernate是Gavin King于2001年开始，作为EJB2风格实体bean的替代品开发的对象关系映射工具  Hibernate官方网站是：http://hibernate.org/ ，有关 Hibernate 的资讯，文档，软件库等都可以这个网站上找到">
<meta name="keywords" content="hibenrate">
<meta property="og:type" content="article">
<meta property="og:title" content="hibernate的基本用法">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-07-31-Hibernate的基本用法/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="##  Hibernate是Gavin King于2001年开始，作为EJB2风格实体bean的替代品开发的对象关系映射工具  Hibernate官方网站是：http://hibernate.org/ ，有关 Hibernate 的资讯，文档，软件库等都可以这个网站上找到">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180731213119.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/604080357_24119%20%281%29.jpg">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/173090306_68782.jpg">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180801163157.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/570140515_19159.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/734140525_97762.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/931170555_26701.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/689170557_42799.png">
<meta property="og:image" content="http://www.yiibai.com/uploads/images/201705/1005/149140528_88930.png">
<meta property="og:image" content="http://www.yiibai.com/uploads/images/201705/0905/931170555_26701.png">
<meta property="og:image" content="http://www.yiibai.com/uploads/images/201705/0905/689170557_42799.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/538100537_54337.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/839140534_80005%20%281%29.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/001.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180802195211.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180802202703.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/892100550_69590.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180803114430.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/721100554_22650.png">
<meta property="og:updated_time" content="2018-11-01T14:24:04.972Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="hibernate的基本用法">
<meta name="twitter:description" content="##  Hibernate是Gavin King于2001年开始，作为EJB2风格实体bean的替代品开发的对象关系映射工具  Hibernate官方网站是：http://hibernate.org/ ，有关 Hibernate 的资讯，文档，软件库等都可以这个网站上找到">
<meta name="twitter:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180731213119.png">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-07-31-Hibernate的基本用法" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-07-31-Hibernate的基本用法/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      hibernate的基本用法
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>## </p>
<p>Hibernate是Gavin King于2001年开始，作为EJB2风格实体<code>bean</code>的替代品开发的对象关系映射工具 </p>
<p>Hibernate官方网站是：<a href="http://hibernate.org/" target="_blank" rel="noopener">http://hibernate.org/</a> ，有关 <strong>Hibernate</strong> 的资讯，文档，软件库等都可以这个网站上找到 </p>
<a id="more"></a>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180731213119.png" alt="1"></p>
<h2 id="hibernate-框架"><a href="#hibernate-框架" class="headerlink" title="hibernate 框架"></a>hibernate 框架</h2><p><img src="http://p1aoqp63y.bkt.clouddn.com/604080357_24119%20%281%29.jpg" alt="1"></p>
<p>Hibernate框架简化了java应用程序与数据库交互的开发。 Hibernate是一个开源，轻量级的ORM(对象关系映射)工具。</p>
<p>ORM工具简化了数据创建，数据处理和数据访问。它是将对象映射到数据库中存储的数据(表)的编程技术</p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/173090306_68782.jpg" alt="2"></p>
<h3 id="hibernate体系架构要素"><a href="#hibernate体系架构要素" class="headerlink" title="hibernate体系架构要素"></a>hibernate体系架构要素</h3><p><strong>会话工厂(SessionFactory)</strong></p>
<p><code>SessionFactory</code>是<code>ConnectionProvider</code>的会话和客户端工厂。 它拥有数据的二级缓存(可选)。 <code>org.hibernate.SessionFactory</code>接口提供了工厂方法来获取<code>Session</code>的对象。</p>
<p><strong>会话(Session)</strong><br>Session对象提供应用程序和存储在数据库中的数据之间的接口。 它是一个短生命周期的对象并包装JDBC连接。 它是事务，查询和标准的工厂。 它拥有一级缓存(强制性)数据。 <code>org.hibernate.Session</code>接口提供插入，更新和删除对象的方法。 它还提供了事务，查询和标准的工厂方法。</p>
<p><strong>事务(Transaction)</strong><br>事务对象指定工作的原子单位,它是一个可选项。 <code>org.hibernate.Transaction</code>接口提供事务管理的方法。</p>
<p><strong>连接提供者(ConnectionProvider)</strong></p>
<p>它是一个JDBC连接工厂。 它从<code>DriverManager</code>或<code>DataSource</code>抽象出来的应用程序。 它是一个可选项。</p>
<p><strong>事务工厂(TransactionFactory)</strong></p>
<p>它是一个事务工厂，是一个可选项。</p>
<h2 id="hibernate的入门程序"><a href="#hibernate的入门程序" class="headerlink" title="hibernate的入门程序"></a>hibernate的入门程序</h2><p>数据库设计如下:</p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180801163157.png" alt="1"></p>
<h2 id="1-配置hibernate"><a href="#1-配置hibernate" class="headerlink" title="1. 配置hibernate"></a>1. 配置hibernate</h2><p>配置hibernate目的是让Hibernate可以连接数据库并与数据库交互，并声明在前面的步骤中创建的实体列表。</p>
<p>在<em>src/main/java</em>中创建一个名称为：<em>hibernate.cfg.xml</em> 的配置文件，当前项目结构如下图所示 -</p>
<p><em>hibernate.cfg.xml</em> 配置文件的内容如下所示 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&apos;1.0&apos; encoding=&apos;utf-8&apos;?&gt;</span><br><span class="line">&lt;!DOCTYPE hibernate-configuration PUBLIC</span><br><span class="line">&quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;</span><br><span class="line">&quot;http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt;</span><br><span class="line"></span><br><span class="line">&lt;hibernate-configuration&gt;</span><br><span class="line"></span><br><span class="line">  &lt;session-factory&gt;</span><br><span class="line">      &lt;!-- Database connection settings --&gt;</span><br><span class="line">      &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;</span><br><span class="line">      &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&lt;/property&gt;</span><br><span class="line">      &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;</span><br><span class="line">      &lt;property name=&quot;connection.password&quot;&gt;123456&lt;/property&gt;</span><br><span class="line"></span><br><span class="line">      &lt;!-- JDBC connection pool (use the built-in) --&gt;</span><br><span class="line">      &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;</span><br><span class="line"></span><br><span class="line">      &lt;!-- SQL dialect --&gt;</span><br><span class="line">      &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;</span><br><span class="line"></span><br><span class="line">      &lt;!-- Enable Hibernate&apos;s automatic session context management --&gt;</span><br><span class="line">      &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;</span><br><span class="line"></span><br><span class="line">      &lt;!-- Disable the second-level cache --&gt;</span><br><span class="line">      &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.internal.NoCacheProvider&lt;/property&gt;</span><br><span class="line"></span><br><span class="line">      &lt;!-- Echo all executed SQL to stdout --&gt;</span><br><span class="line">      &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;</span><br><span class="line"></span><br><span class="line">      &lt;mapping class=&quot;com.yiibai.entities.Department&quot; /&gt;</span><br><span class="line">      &lt;mapping class=&quot;com.yiibai.entities.Employee&quot; /&gt;</span><br><span class="line">      &lt;mapping class=&quot;com.yiibai.entities.SalaryGrade&quot; /&gt;</span><br><span class="line">      &lt;mapping class=&quot;com.yiibai.entities.Timekeeper&quot; /&gt;</span><br><span class="line"></span><br><span class="line">  &lt;/session-factory&gt;</span><br><span class="line"></span><br><span class="line">&lt;/hibernate-configuration&gt;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">XML</span><br></pre></td></tr></table></figure>
<p>每种数据库都有一个单独的方言， 例如：</p>
<p><strong>SQL Server方言：</strong></p>
<ul>
<li>org.hibernate.dialect.SQLServerDialect并</li>
<li>org.hibernate.dialect.SQLServer2012Dialect</li>
<li>org.hibernate.dialect.SQLServer2008Dialect</li>
</ul>
<p><strong>MySQL方言</strong></p>
<ul>
<li>org.hibernate.dialect.MySQLDialect</li>
<li>org.hibernate.dialect.MySQL5Dialect</li>
</ul>
<h3 id="什么是方言？"><a href="#什么是方言？" class="headerlink" title="什么是方言？"></a>什么是方言？</h3><p><code>Dialect</code>是一个使用Hibernate的方式将数据库的数据类型转换为Java的数据类型，反之亦然。此外，它用于定义将HSQL(Hibernate SQL)的函数转换为数据中的函数的方式，如下列出的一部分 -</p>
<table>
<thead>
<tr>
<th>Java SQL类型</th>
<th>Oracle</th>
<th>MySQL</th>
<th>SQL Server</th>
</tr>
</thead>
<tbody>
<tr>
<td>Types.BIT</td>
<td>number(1,0)</td>
<td>bit</td>
<td>bit</td>
</tr>
<tr>
<td>Types.BIGINT</td>
<td>number(19,0)</td>
<td>bigin</td>
<td>bigint</td>
</tr>
<tr>
<td>Types.DATE</td>
<td>date</td>
<td>date</td>
<td>date</td>
</tr>
<tr>
<td>…….</td>
<td>…</td>
<td>…</td>
<td>…</td>
</tr>
<tr>
<td>Types.CLOB</td>
<td>clob</td>
<td>longtext</td>
<td>varchar(MAX)</td>
</tr>
<tr>
<td>Types.BLOB</td>
<td>blob</td>
<td>longblob</td>
<td>varbinary(MAX)</td>
</tr>
</tbody>
</table>
<h2 id="数据库表对应的实体类"><a href="#数据库表对应的实体类" class="headerlink" title="数据库表对应的实体类"></a>数据库表对应的实体类</h2><p>这几个类的代码，分别如下所示 -</p>
<p><em>Department.java</em> 类代码 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line">package com.anlu.hibernate.entity;</span><br><span class="line"></span><br><span class="line">import java.util.HashSet;</span><br><span class="line">import java.util.Set;</span><br><span class="line"></span><br><span class="line">import javax.persistence.Column;</span><br><span class="line">import javax.persistence.Entity;</span><br><span class="line">import javax.persistence.FetchType;</span><br><span class="line">import javax.persistence.Id;</span><br><span class="line">import javax.persistence.OneToMany;</span><br><span class="line">import javax.persistence.Table;</span><br><span class="line">import javax.persistence.UniqueConstraint;</span><br><span class="line"></span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;DEPARTMENT&quot;, uniqueConstraints = &#123; @UniqueConstraint(columnNames = &#123; &quot;DEPT_NO&quot; &#125;) &#125;)</span><br><span class="line">public class Department &#123;</span><br><span class="line"></span><br><span class="line">    private Integer deptId;</span><br><span class="line">    private String deptNo;</span><br><span class="line"></span><br><span class="line">    private String deptName;</span><br><span class="line">    private String location;</span><br><span class="line">    private Set&lt;Employee&gt; employees = new HashSet&lt;Employee&gt;(0);</span><br><span class="line"></span><br><span class="line">    public Department() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Department(Integer deptId, String deptName, String location) &#123;</span><br><span class="line">        this.deptId = deptId;</span><br><span class="line">        this.deptNo = &quot;D&quot; + this.deptId;</span><br><span class="line">        this.deptName = deptName;</span><br><span class="line">        this.location = location;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Id</span><br><span class="line">    @Column(name = &quot;DEPT_ID&quot;)</span><br><span class="line">    public Integer getDeptId() &#123;</span><br><span class="line">        return deptId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setDeptId(Integer deptId) &#123;</span><br><span class="line">        this.deptId = deptId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;DEPT_NO&quot;, length = 20, nullable = false)</span><br><span class="line">    public String getDeptNo() &#123;</span><br><span class="line">        return deptNo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setDeptNo(String deptNo) &#123;</span><br><span class="line">        this.deptNo = deptNo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;DEPT_NAME&quot;, nullable = false)</span><br><span class="line">    public String getDeptName() &#123;</span><br><span class="line">        return deptName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setDeptName(String deptName) &#123;</span><br><span class="line">        this.deptName = deptName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;LOCATION&quot;)</span><br><span class="line">    public String getLocation() &#123;</span><br><span class="line">        return location;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setLocation(String location) &#123;</span><br><span class="line">        this.location = location;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;department&quot;)</span><br><span class="line">    public Set&lt;Employee&gt; getEmployees() &#123;</span><br><span class="line">        return employees;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmployees(Set&lt;Employee&gt; employees) &#123;</span><br><span class="line">        this.employees = employees;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Java</span><br></pre></td></tr></table></figure>
<p><em>Employee.java</em> 类代码 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br></pre></td><td class="code"><pre><span class="line">package com.anlu.hibernate.entity;</span><br><span class="line"></span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.HashSet;</span><br><span class="line">import java.util.Set;</span><br><span class="line"></span><br><span class="line">import javax.persistence.Column;</span><br><span class="line">import javax.persistence.Entity;</span><br><span class="line">import javax.persistence.FetchType;</span><br><span class="line">import javax.persistence.Id;</span><br><span class="line">import javax.persistence.JoinColumn;</span><br><span class="line">import javax.persistence.Lob;</span><br><span class="line">import javax.persistence.ManyToOne;</span><br><span class="line">import javax.persistence.OneToMany;</span><br><span class="line">import javax.persistence.Table;</span><br><span class="line">import javax.persistence.Temporal;</span><br><span class="line">import javax.persistence.TemporalType;</span><br><span class="line">import javax.persistence.UniqueConstraint;</span><br><span class="line"></span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;EMPLOYEE&quot;, uniqueConstraints = &#123; @UniqueConstraint(columnNames = &#123; &quot;EMP_NO&quot; &#125;) &#125;)</span><br><span class="line">public class Employee &#123;</span><br><span class="line">    private Long empId;</span><br><span class="line">    private String empNo;</span><br><span class="line"></span><br><span class="line">    private String empName;</span><br><span class="line">    private String job;</span><br><span class="line">    private Employee manager;</span><br><span class="line">    private Date hideDate;</span><br><span class="line">    private Float salary;</span><br><span class="line">    private byte[] image;</span><br><span class="line"></span><br><span class="line">    private Department department;</span><br><span class="line">    private Set&lt;Employee&gt; employees = new HashSet&lt;Employee&gt;(0);</span><br><span class="line"></span><br><span class="line">    public Employee() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Employee(Long empId, String empName, String job, Employee manager, Date hideDate, Float salary, Float comm,</span><br><span class="line">            Department department) &#123;</span><br><span class="line">        this.empId = empId;</span><br><span class="line">        this.empNo = &quot;E&quot; + this.empId;</span><br><span class="line">        this.empName = empName;</span><br><span class="line">        this.job = job;</span><br><span class="line">        this.manager = manager;</span><br><span class="line">        this.hideDate = hideDate;</span><br><span class="line">        this.salary = salary;</span><br><span class="line">        this.department = department;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Id</span><br><span class="line">    @Column(name = &quot;EMP_ID&quot;)</span><br><span class="line">    public Long getEmpId() &#123;</span><br><span class="line">        return empId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmpId(Long empId) &#123;</span><br><span class="line">        this.empId = empId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;EMP_NO&quot;, length = 20, nullable = false)</span><br><span class="line">    public String getEmpNo() &#123;</span><br><span class="line">        return empNo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmpNo(String empNo) &#123;</span><br><span class="line">        this.empNo = empNo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;EMP_NAME&quot;, length = 50, nullable = false)</span><br><span class="line">    public String getEmpName() &#123;</span><br><span class="line">        return empName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmpName(String empName) &#123;</span><br><span class="line">        this.empName = empName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;JOB&quot;, length = 30, nullable = false)</span><br><span class="line">    public String getJob() &#123;</span><br><span class="line">        return job;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setJob(String job) &#123;</span><br><span class="line">        this.job = job;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @ManyToOne(fetch = FetchType.LAZY)</span><br><span class="line">    @JoinColumn(name = &quot;MNG_ID&quot;)</span><br><span class="line">    public Employee getManager() &#123;</span><br><span class="line">        return manager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setManager(Employee manager) &#123;</span><br><span class="line">        this.manager = manager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;HIRE_DATE&quot;, nullable = false)</span><br><span class="line">    @Temporal(TemporalType.DATE)</span><br><span class="line">    public Date getHideDate() &#123;</span><br><span class="line">        return hideDate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setHideDate(Date hideDate) &#123;</span><br><span class="line">        this.hideDate = hideDate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;SALARY&quot;, nullable = false)</span><br><span class="line">    public Float getSalary() &#123;</span><br><span class="line">        return salary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setSalary(Float salary) &#123;</span><br><span class="line">        this.salary = salary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;IMAGE&quot;, length = 1111111, nullable = true)</span><br><span class="line">    @Lob</span><br><span class="line">    public byte[] getImage() &#123;</span><br><span class="line">        return image;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setImage(byte[] image) &#123;</span><br><span class="line">        this.image = image;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @ManyToOne(fetch = FetchType.LAZY)</span><br><span class="line">    @JoinColumn(name = &quot;DEPT_ID&quot;, nullable = false)</span><br><span class="line">    public Department getDepartment() &#123;</span><br><span class="line">        return department;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setDepartment(Department department) &#123;</span><br><span class="line">        this.department = department;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;empId&quot;)</span><br><span class="line">    public Set&lt;Employee&gt; getEmployees() &#123;</span><br><span class="line">        return employees;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmployees(Set&lt;Employee&gt; employees) &#123;</span><br><span class="line">        this.employees = employees;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Java</span><br></pre></td></tr></table></figure>
<p><em>SalaryGrade.java</em> 类代码 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">packagecom com.anlu.hibernate.entity;</span><br><span class="line"></span><br><span class="line">import javax.persistence.Column;</span><br><span class="line">import javax.persistence.Entity;</span><br><span class="line">import javax.persistence.Id;</span><br><span class="line">import javax.persistence.Table;</span><br><span class="line"></span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;SALARY_GRADE&quot;)</span><br><span class="line">public class SalaryGrade &#123;</span><br><span class="line">    private Integer grade;</span><br><span class="line">    private Float lowSalary;</span><br><span class="line">    private Float highSalary;</span><br><span class="line"></span><br><span class="line">    public SalaryGrade() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public SalaryGrade(Integer grade, Float lowSalary, Float highSalary) &#123;</span><br><span class="line">        this.grade = grade;</span><br><span class="line">        this.lowSalary = lowSalary;</span><br><span class="line">        this.highSalary = highSalary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Id</span><br><span class="line">    @Column(name = &quot;GRADE&quot;)</span><br><span class="line">    public Integer getGrade() &#123;</span><br><span class="line">        return grade;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setGrade(Integer grade) &#123;</span><br><span class="line">        this.grade = grade;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;LOW_SALARY&quot;, nullable = false)</span><br><span class="line">    public Float getLowSalary() &#123;</span><br><span class="line">        return lowSalary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setLowSalary(Float lowSalary) &#123;</span><br><span class="line">        this.lowSalary = lowSalary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;HIGH_SALARY&quot;, nullable = false)</span><br><span class="line">    public Float getHighSalary() &#123;</span><br><span class="line">        return highSalary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setHighSalary(Float highSalary) &#123;</span><br><span class="line">        this.highSalary = highSalary;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Java</span><br></pre></td></tr></table></figure>
<p><em>Timekeeper.java</em> 类代码 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line">package com.anlu.hibernate.entity;</span><br><span class="line"></span><br><span class="line">import java.util.Date;</span><br><span class="line"></span><br><span class="line">import javax.persistence.Column;</span><br><span class="line">import javax.persistence.Entity;</span><br><span class="line">import javax.persistence.FetchType;</span><br><span class="line">import javax.persistence.GeneratedValue;</span><br><span class="line">import javax.persistence.Id;</span><br><span class="line">import javax.persistence.JoinColumn;</span><br><span class="line">import javax.persistence.ManyToOne;</span><br><span class="line">import javax.persistence.Table;</span><br><span class="line">import javax.persistence.Temporal;</span><br><span class="line">import javax.persistence.TemporalType;</span><br><span class="line"></span><br><span class="line">import org.hibernate.annotations.GenericGenerator;</span><br><span class="line"></span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;TIMEKEEPER&quot;)</span><br><span class="line">public class Timekeeper &#123;</span><br><span class="line">    public static final char IN = &apos;I&apos;;</span><br><span class="line">    public static final char OUT = &apos;O&apos;;</span><br><span class="line"></span><br><span class="line">    private String timekeeperId;</span><br><span class="line"></span><br><span class="line">    private Date dateTime;</span><br><span class="line"></span><br><span class="line">    private Employee employee;</span><br><span class="line"></span><br><span class="line">    // &apos;I&apos; or &apos;O&apos;</span><br><span class="line">    private char inOut;</span><br><span class="line"></span><br><span class="line">    @Id</span><br><span class="line">    @GeneratedValue(generator = &quot;uuid&quot;)</span><br><span class="line">    @GenericGenerator(name = &quot;uuid&quot;, strategy = &quot;uuid2&quot;)</span><br><span class="line">    @Column(name = &quot;Timekeeper_Id&quot;, length = 36)</span><br><span class="line">    public String getTimekeeperId() &#123;</span><br><span class="line">        return timekeeperId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setTimekeeperId(String timekeeperId) &#123;</span><br><span class="line">        this.timekeeperId = timekeeperId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;Date_Time&quot;, nullable = false)</span><br><span class="line">    @Temporal(TemporalType.TIMESTAMP)</span><br><span class="line">    public Date getDateTime() &#123;</span><br><span class="line">        return dateTime;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setDateTime(Date dateTime) &#123;</span><br><span class="line">        this.dateTime = dateTime;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @ManyToOne(fetch = FetchType.LAZY)</span><br><span class="line">    @JoinColumn(name = &quot;EMP_ID&quot;, nullable = false)</span><br><span class="line">    public Employee getEmployee() &#123;</span><br><span class="line">        return employee;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmployee(Employee employee) &#123;</span><br><span class="line">        this.employee = employee;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Column(name = &quot;In_Out&quot;, nullable = false, length = 1)</span><br><span class="line">    public char getInOut() &#123;</span><br><span class="line">        return inOut;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setInOut(char inOut) &#123;</span><br><span class="line">        this.inOut = inOut;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="2-Hibernate查询语言-HQL"><a href="#2-Hibernate查询语言-HQL" class="headerlink" title="2. Hibernate查询语言(HQL)"></a>2. Hibernate查询语言(HQL)</h2><p>Hibernate使用Hibernate查询语言(HQL)查询数据。 HQL与我们所了解的数据库SQL语句有点不同。</p>
<p><strong>SQL：</strong></p>
<ul>
<li>在表中查询数据</li>
</ul>
<p><strong>HQL：</strong></p>
<ul>
<li>在实体类中查询对象数据</li>
</ul>
<p>参考比较以下用法 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">-- SQL</span><br><span class="line">-- This is a SQL query in table DEPARTMENT.</span><br><span class="line">Select d.DEPT_NO, d.DEPT_NAME from DEPARTMENT d;</span><br><span class="line"></span><br><span class="line">-- HQL</span><br><span class="line">-- This is a HQL query in Entity Department.</span><br><span class="line">Select d.deptNo, d.deptName from Department d;</span><br><span class="line"></span><br><span class="line">-- Query Object</span><br><span class="line">Select d from Department d;</span><br></pre></td></tr></table></figure>
<p><strong>Hibernate的操作规则：</strong></p>
<p>应用程序编写的HQL在操作过程中，Hibernate本身就意识到它使用的数据库类型(如：MySQL)，它会自动将HQL转换为等价的数据库类型的SQL形式。 事实上，各种类型的数据库之间的SQL语法有一些差异，比如：返回记录的行数的限制就不同(MySQL中使用 <code>limit</code> 子句)。</p>
<blockquote>
<p>可以参考HQL语法： <a href="http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/queryhql.html" target="_blank" rel="noopener">http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/queryhql.html</a></p>
</blockquote>
<h2 id="3-使用Hibernate查询数据"><a href="#3-使用Hibernate查询数据" class="headerlink" title="3. 使用Hibernate查询数据"></a>3. 使用Hibernate查询数据</h2><p>在Hibernate中有很多方法可以用来查询数据。在这部分中，将介绍一些查询数据的典型方法。</p>
<p>使用junit4.7进行测试</p>
<p>创建一个Hqltest类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"> public class HqlTest  &#123;</span><br><span class="line"></span><br><span class="line">   private SessionFactory sessionFactory;</span><br><span class="line">   private Session session ;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   @Before</span><br><span class="line">  public void before()&#123;</span><br><span class="line">       sessionFactory=HibernateUtils.getSessionFactory();</span><br><span class="line">       session = sessionFactory.getCurrentSession();</span><br><span class="line"></span><br><span class="line">       // All the action with DB via Hibernate</span><br><span class="line">       // must be located in one transaction.</span><br><span class="line">       // Start Transaction.</span><br><span class="line">       session.getTransaction().begin();</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  @After</span><br><span class="line">  public void after()&#123;</span><br><span class="line">      // Commit data.</span><br><span class="line">      session.getTransaction().commit();</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-1-使用HQL的查询对象"><a href="#3-1-使用HQL的查询对象" class="headerlink" title="3.1 - 使用HQL的查询对象"></a>3.1 - 使用HQL的查询对象</h3><p><strong>查询对象示例-1</strong> 第一个例子，使用HQL查询对象(Entity)，其代码如下 - </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">   * 测试查询员工集合</span><br><span class="line">   */</span><br><span class="line">  @Test</span><br><span class="line"> public void testSelectEmployee()&#123;</span><br><span class="line"></span><br><span class="line">     try &#123;</span><br><span class="line">         // Create an HQL statement, query the object.</span><br><span class="line">         // Equivalent to the SQL statement:</span><br><span class="line">         // Select e.* from EMPLOYEE e order by e.EMP_NAME, e.EMP_NO</span><br><span class="line">         String sql = &quot;Select e from &quot; + Employee.class.getName() + &quot; e &quot;</span><br><span class="line">                 + &quot; order by e.empName, e.empNo &quot;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">         // Create Query object.</span><br><span class="line">         Query query = session.createQuery(sql);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">         // Execute query.</span><br><span class="line">         List&lt;Employee&gt; employees = query.getResultList();</span><br><span class="line"></span><br><span class="line">         for (Employee emp : employees) &#123;</span><br><span class="line">             System.out.println(&quot;Emp: &quot; + emp.getEmpNo() + &quot; : &quot;</span><br><span class="line">                     + emp.getEmpName());</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">     &#125; catch (Exception e) &#123;</span><br><span class="line">         e.printStackTrace();</span><br><span class="line">         // Rollback in case of an error occurred.</span><br><span class="line">         session.getTransaction().rollback();</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/570140515_19159.png" alt="2"></p>
<p><strong>查询对象示例-2</strong> </p>
<p>查询带参数的hql</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">  * 第二個查詢员工表方法</span><br><span class="line">  */</span><br><span class="line"> @Test</span><br><span class="line">public void testSelectEmp2()&#123;</span><br><span class="line">    // Create an HQL statement, query the object.</span><br><span class="line">    // HQL with parameters.</span><br><span class="line">    // Equivalent to the SQL statement:</span><br><span class="line">    // Select e.* from EMPLOYEE e cross join DEPARTMENT d</span><br><span class="line">    // where e.DEPT_ID = d.DEPT_ID and d.DEPT_NO = :deptNo;</span><br><span class="line">    String sql = &quot;Select e from &quot; + Employee.class.getName() + &quot; e &quot; + &quot; where e.department.deptNo=:deptNo &quot;;</span><br><span class="line"></span><br><span class="line">    // Create query object.</span><br><span class="line">    Query&lt;Employee&gt; query = session.createQuery(sql);</span><br><span class="line"></span><br><span class="line">    query.setParameter(&quot;deptNo&quot;, &quot;D10&quot;);</span><br><span class="line"></span><br><span class="line">    // Execute query.</span><br><span class="line">    List&lt;Employee&gt; employees = query.getResultList();</span><br><span class="line"></span><br><span class="line">    for (Employee emp : employees) &#123;</span><br><span class="line">        System.out.println(&quot;Emp: &quot; + emp.getEmpNo() + &quot; : &quot; + emp.getEmpName());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="查询多列的值"><a href="#查询多列的值" class="headerlink" title="查询多列的值"></a>查询多列的值</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">  * 查询多列的值</span><br><span class="line">  */</span><br><span class="line">@Test</span><br><span class="line">public void testSomeColumn()&#123;</span><br><span class="line"></span><br><span class="line">    // Query some columns.</span><br><span class="line">    String sql = &quot;Select e.empId, e.empNo, e.empName from &quot;</span><br><span class="line">            + Employee.class.getName() + &quot; e &quot;;</span><br><span class="line"></span><br><span class="line">    Query&lt;Object[]&gt; query = session.createQuery(sql);</span><br><span class="line"></span><br><span class="line">    // Execute Query.</span><br><span class="line">    // Get the array of Object</span><br><span class="line">    List&lt;Object[]&gt; datas = query.getResultList();</span><br><span class="line"></span><br><span class="line">    for (Object[] emp : datas) &#123;</span><br><span class="line">        System.out.println(&quot;Emp Id: &quot; + emp[0]);</span><br><span class="line">        System.out.println(&quot;    Emp No: &quot; + emp[1]);</span><br><span class="line">        System.out.println(&quot;    Emp Name: &quot; + emp[2]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="使用HQL和JavaBean查询多列数据"><a href="#使用HQL和JavaBean查询多列数据" class="headerlink" title="使用HQL和JavaBean查询多列数据"></a>使用HQL和JavaBean查询多列数据</h3><p>在这种情况下，如果需要在某些表中提取某些列的数据，最好的方法是使用Java bean。使用Java bean的构造函数来为不同的字段设置值。在此构造函数加入HQL查询。 </p>
<p>创建一个Java类文件：<em>ShortEmpInfo.java</em>，其代码如下 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">package com.anlu.hibernate.entity;</span><br><span class="line"></span><br><span class="line">public class ShortEmpInfo &#123;</span><br><span class="line">    private Long empId;</span><br><span class="line">    private String empNo;</span><br><span class="line">    private String empName;</span><br><span class="line"></span><br><span class="line">    //</span><br><span class="line">    // Constructor have 3 parameters, will be used in the Hibernate Query.</span><br><span class="line">    //</span><br><span class="line">    public ShortEmpInfo(Long empId, String empNo, String empName) &#123;</span><br><span class="line">        this.empId = empId;</span><br><span class="line">        this.empNo = empNo;</span><br><span class="line">        this.empName = empName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Long getEmpId() &#123;</span><br><span class="line">        return empId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmpId(Long empId) &#123;</span><br><span class="line">        this.empId = empId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getEmpNo() &#123;</span><br><span class="line">        return empNo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmpNo(String empNo) &#123;</span><br><span class="line">        this.empNo = empNo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getEmpName() &#123;</span><br><span class="line">        return empName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setEmpName(String empName) &#123;</span><br><span class="line">        this.empName = empName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="测试如下"><a href="#测试如下" class="headerlink" title="测试如下"></a>测试如下</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">   * 如果需要在某些表中提取某些列的数据，</span><br><span class="line">   * 最好的方法是使用Java bean。</span><br><span class="line">   * 使用Java bean的构造函数来为不同的字段设置值。在此构造函数加入HQL查询</span><br><span class="line">   */</span><br><span class="line">  @Test</span><br><span class="line"> public void testShortEmpQuary()&#123;</span><br><span class="line">      // Using constructor of ShortEmpInfo</span><br><span class="line">      String sql = &quot;Select new &quot; + ShortEmpInfo.class.getName()</span><br><span class="line">              + &quot;(e.empId, e.empNo, e.empName)&quot; + &quot; from &quot;</span><br><span class="line">              + Employee.class.getName() + &quot; e &quot;;</span><br><span class="line"></span><br><span class="line">      Query&lt;ShortEmpInfo&gt; query = session.createQuery(sql);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      // Execute query.</span><br><span class="line">      // Get a List of ShortEmpInfo</span><br><span class="line">      List&lt;ShortEmpInfo&gt; employees = query.getResultList();</span><br><span class="line"></span><br><span class="line">      for (ShortEmpInfo emp : employees) &#123;</span><br><span class="line">          System.out.println(&quot;Emp: &quot; + emp.getEmpNo() + &quot; : &quot;</span><br><span class="line">                  + emp.getEmpName());</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<h4 id="查询检索唯一结果"><a href="#查询检索唯一结果" class="headerlink" title="查询检索唯一结果"></a>查询检索唯一结果</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">  //============私有方法==============</span><br><span class="line">  public static Department getDepartment(Session session, String deptNo) &#123;</span><br><span class="line">      String sql = &quot;Select d from &quot; + Department.class.getName() + &quot; d &quot;//</span><br><span class="line">              + &quot; where d.deptNo= :deptNo &quot;;</span><br><span class="line">      Query&lt;Department&gt; query = session.createQuery(sql);</span><br><span class="line">      query.setParameter(&quot;deptNo&quot;, deptNo);</span><br><span class="line">      return (Department) query.getSingleResult();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  public static Employee getEmployee(Session session, Long empId) &#123;</span><br><span class="line">      String sql = &quot;Select e from &quot; + Employee.class.getName() + &quot; e &quot;//</span><br><span class="line">              + &quot; where e.empId= :empId &quot;;</span><br><span class="line">      Query&lt;Employee&gt; query = session.createQuery(sql);</span><br><span class="line">      query.setParameter(&quot;empId&quot;, empId);</span><br><span class="line">      return (Employee) query.getSingleResult();</span><br><span class="line">  &#125;</span><br><span class="line">/**</span><br><span class="line">   * 查询唯一结果</span><br><span class="line">   */</span><br><span class="line">  @Test</span><br><span class="line"> public void testUniqueResult()&#123;</span><br><span class="line"></span><br><span class="line">     Department dept = getDepartment(session, &quot;D10&quot;);</span><br><span class="line">     Set&lt;Employee&gt; emps = dept.getEmployees();</span><br><span class="line"></span><br><span class="line">     System.out.println(&quot;Dept Name: &quot; + dept.getDeptName());</span><br><span class="line">     for (Employee emp : emps) &#123;</span><br><span class="line">         System.out.println(&quot; Emp name: &quot; + emp.getEmpName());</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     Employee emp = getEmployee(session, 7839L);</span><br><span class="line">     System.out.println(&quot;Emp Name: &quot; + emp.getEmpName());</span><br><span class="line"></span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>效果如下:</p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/734140525_97762.png" alt="1"></p>
<h3 id="4-Hibernate瞬态，持久和分离"><a href="#4-Hibernate瞬态，持久和分离" class="headerlink" title="4.Hibernate瞬态，持久和分离"></a>4.Hibernate瞬态，持久和分离</h3><p>在这部分中，使用<code>Session.persist(Object)</code>将瞬态对象插入数据库的简单示例。本例中将介绍对象瞬态(Transitent)，持久(Persistent)和分离(Detached)的概念。</p>
<p>创建一个Java类文件：<em>DataUtils.java</em>，其代码如下 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">package com.anlu.hibernate.utils;</span><br><span class="line"></span><br><span class="line">import com.anlu.hibernate.entity.Department;</span><br><span class="line">import com.anlu.hibernate.entity.Employee;</span><br><span class="line">import org.hibernate.Session;</span><br><span class="line">import org.hibernate.query.Query;</span><br><span class="line"></span><br><span class="line">public class DataUtils &#123;</span><br><span class="line"></span><br><span class="line">    public static Department findDepartment(Session session, String deptNo) &#123;</span><br><span class="line">        String sql = &quot;Select d from &quot; + Department.class.getName() + &quot; d &quot;//</span><br><span class="line">                + &quot; Where d.deptNo = :deptNo&quot;;</span><br><span class="line">        Query&lt;Department&gt; query = session.createQuery(sql);</span><br><span class="line">        query.setParameter(&quot;deptNo&quot;, deptNo);</span><br><span class="line">        return query.getSingleResult();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static Long getMaxEmpId(Session session) &#123;</span><br><span class="line">        String sql = &quot;Select max(e.empId) from &quot; + Employee.class.getName() + &quot; e &quot;;</span><br><span class="line">        Query&lt;Number&gt; query = session.createQuery(sql);</span><br><span class="line">        Number value = query.getSingleResult();</span><br><span class="line">        if (value == null) &#123;</span><br><span class="line">            return 0L;</span><br><span class="line">        &#125;</span><br><span class="line">        return value.longValue();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static Employee findEmployee(Session session, String empNo) &#123;</span><br><span class="line">        String sql = &quot;Select e from &quot; + Employee.class.getName() + &quot; e &quot;//</span><br><span class="line">                + &quot; Where e.empNo = :empNo&quot;;</span><br><span class="line">        Query&lt;Employee&gt; query = session.createQuery(sql);</span><br><span class="line">        query.setParameter(&quot;empNo&quot;, empNo);</span><br><span class="line">        return query.getSingleResult();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>测试：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">//---------------------PersistDemo------------------</span><br><span class="line">   @Test</span><br><span class="line">   public void testPersist()&#123;</span><br><span class="line">       Department department = null;</span><br><span class="line">       Employee emp = null;</span><br><span class="line">       try &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">           Long maxEmpId = DataUtils.getMaxEmpId(session);</span><br><span class="line">           Long empId = maxEmpId + 1;</span><br><span class="line"></span><br><span class="line">           // Get Persistent object.</span><br><span class="line">           department = DataUtils.findDepartment(session, &quot;D10&quot;);</span><br><span class="line"></span><br><span class="line">           // Create transient object</span><br><span class="line">           emp = new Employee();</span><br><span class="line">           emp.setEmpId(empId);</span><br><span class="line">           emp.setEmpNo(&quot;E&quot; + empId);</span><br><span class="line">           emp.setEmpName(&quot;Name &quot; + empId);</span><br><span class="line">           emp.setJob(&quot;Coder&quot;);</span><br><span class="line">           emp.setSalary(1000f);</span><br><span class="line">           emp.setManager(null);</span><br><span class="line">           emp.setHideDate(new Date());</span><br><span class="line">           emp.setDepartment(department);</span><br><span class="line"></span><br><span class="line">           // Using persist(..)</span><br><span class="line">           // Now &apos;emp&apos; is managed by Hibernate.</span><br><span class="line">           // it has Persistent status.</span><br><span class="line">           // No action at this time with DB.</span><br><span class="line">           session.persist(emp);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">           // At this step the data is pushed to the DB.</span><br><span class="line">           // Execute Insert statement.</span><br><span class="line"></span><br><span class="line">       &#125; catch (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">           session.getTransaction().rollback();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       // After the session is closed (commit, rollback, close)</span><br><span class="line">       // Objects &apos;emp&apos;, &apos;dept&apos; became the Detached objects.</span><br><span class="line">       // It is no longer in the control of the session.</span><br><span class="line">       System.out.println(&quot;Emp No: &quot; + emp.getEmpNo());</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-Hibernate的生命周期"><a href="#5-Hibernate的生命周期" class="headerlink" title="5.Hibernate的生命周期"></a>5.Hibernate的生命周期</h4><p><img src="http://p1aoqp63y.bkt.clouddn.com/931170555_26701.png" alt="2"></p>
<p>hibernate中的一个对象可以存在于以下四个状态之中的一种:</p>
<ul>
<li><strong>短暂(Transient)</strong></li>
<li><strong>持久(Persistent)</strong></li>
<li><strong>Removed</strong></li>
<li><strong>Detached</strong></li>
</ul>
<p>以上几个状态在下面图中解释： </p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/689170557_42799.png" alt="1"></p>
<p>## </p>
<h2 id="9-Hibernate瞬态，持久和分离"><a href="#9-Hibernate瞬态，持久和分离" class="headerlink" title="9. Hibernate瞬态，持久和分离"></a>9. Hibernate瞬态，持久和分离</h2><p>在这部分中，使用<code>Session.persist(Object)</code>将瞬态对象插入数据库的简单示例。本例中将介绍对象瞬态(Transitent)，持久(Persistent)和分离(Detached)的概念。</p>
<p>创建一个Java类文件：<em>DataUtils.java</em>，其代码如下 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">package com.yiibai;</span><br><span class="line"></span><br><span class="line">import org.hibernate.Session;</span><br><span class="line">import org.hibernate.query.Query;</span><br><span class="line">import com.yiibai.entities.Department;</span><br><span class="line">import com.yiibai.entities.Employee;</span><br><span class="line"></span><br><span class="line">public class DataUtils &#123;</span><br><span class="line"></span><br><span class="line">   public static Department findDepartment(Session session, String deptNo) &#123;</span><br><span class="line">       String sql = &quot;Select d from &quot; + Department.class.getName() + &quot; d &quot;//</span><br><span class="line">               + &quot; Where d.deptNo = :deptNo&quot;;</span><br><span class="line">       Query&lt;Department&gt; query = session.createQuery(sql);</span><br><span class="line">       query.setParameter(&quot;deptNo&quot;, deptNo);</span><br><span class="line">       return query.getSingleResult();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   public static Long getMaxEmpId(Session session) &#123;</span><br><span class="line">       String sql = &quot;Select max(e.empId) from &quot; + Employee.class.getName() + &quot; e &quot;;</span><br><span class="line">       Query&lt;Number&gt; query = session.createQuery(sql);</span><br><span class="line">       Number value = query.getSingleResult();</span><br><span class="line">       if (value == null) &#123;</span><br><span class="line">           return 0L;</span><br><span class="line">       &#125;</span><br><span class="line">       return value.longValue();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   public static Employee findEmployee(Session session, String empNo) &#123;</span><br><span class="line">       String sql = &quot;Select e from &quot; + Employee.class.getName() + &quot; e &quot;//</span><br><span class="line">               + &quot; Where e.empNo = :empNo&quot;;</span><br><span class="line">       Query&lt;Employee&gt; query = session.createQuery(sql);</span><br><span class="line">       query.setParameter(&quot;empNo&quot;, empNo);</span><br><span class="line">       return query.getSingleResult();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Java</span><br></pre></td></tr></table></figure>
<p>创建一个Java类文件：<em>PersistDemo.java</em>，其代码如下 -</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">package com.yiibai;</span><br><span class="line"></span><br><span class="line">import java.util.Date;</span><br><span class="line"></span><br><span class="line">import org.hibernate.Session;</span><br><span class="line">import org.hibernate.SessionFactory;</span><br><span class="line">import com.yiibai.entities.Department;</span><br><span class="line">import com.yiibai.entities.Employee;</span><br><span class="line"></span><br><span class="line">public class PersistDemo &#123;</span><br><span class="line"></span><br><span class="line">   public static void main(String[] args) &#123;</span><br><span class="line"></span><br><span class="line">       SessionFactory factory = HibernateUtils.getSessionFactory();</span><br><span class="line"></span><br><span class="line">       Session session = factory.getCurrentSession();</span><br><span class="line">       Department department = null;</span><br><span class="line">       Employee emp = null;</span><br><span class="line">       try &#123;</span><br><span class="line">           session.getTransaction().begin();</span><br><span class="line"></span><br><span class="line">           Long maxEmpId = DataUtils.getMaxEmpId(session);</span><br><span class="line">           Long empId = maxEmpId + 1;</span><br><span class="line"></span><br><span class="line">           // Get Persistent object.</span><br><span class="line">           department = DataUtils.findDepartment(session, &quot;D10&quot;);</span><br><span class="line"></span><br><span class="line">           // Create transient object</span><br><span class="line">           emp = new Employee();</span><br><span class="line">           emp.setEmpId(empId);</span><br><span class="line">           emp.setEmpNo(&quot;E&quot; + empId);</span><br><span class="line">           emp.setEmpName(&quot;Name &quot; + empId);</span><br><span class="line">           emp.setJob(&quot;Coder&quot;);</span><br><span class="line">           emp.setSalary(1000f);</span><br><span class="line">           emp.setManager(null);</span><br><span class="line">           emp.setHideDate(new Date());</span><br><span class="line">           emp.setDepartment(department);</span><br><span class="line"></span><br><span class="line">           // Using persist(..)</span><br><span class="line">           // Now &apos;emp&apos; is managed by Hibernate.</span><br><span class="line">           // it has Persistent status.</span><br><span class="line">           // No action at this time with DB.</span><br><span class="line">           session.persist(emp);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">           // At this step the data is pushed to the DB.</span><br><span class="line">           // Execute Insert statement.</span><br><span class="line">           session.getTransaction().commit();</span><br><span class="line">       &#125; catch (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">           session.getTransaction().rollback();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       // After the session is closed (commit, rollback, close)</span><br><span class="line">       // Objects &apos;emp&apos;, &apos;dept&apos; became the Detached objects.</span><br><span class="line">       // It is no longer in the control of the session.        </span><br><span class="line">       System.out.println(&quot;Emp No: &quot; + emp.getEmpNo());</span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Java</span><br></pre></td></tr></table></figure>
<p>运行上面代码，得到以下结果 -</p>
<p><img src="http://www.yiibai.com/uploads/images/201705/1005/149140528_88930.png" alt="img"></p>
<h2 id="10-Hibernate生命周期"><a href="#10-Hibernate生命周期" class="headerlink" title="10. Hibernate生命周期"></a>10. Hibernate生命周期</h2><p>Hibernate的Session类的有一些/几组的重要方法，如下图所示：</p>
<p><img src="http://www.yiibai.com/uploads/images/201705/0905/931170555_26701.png" alt="img"></p>
<p>Hibernate中的一个对象存在于以下四个状态之中的一种：</p>
<ul>
<li><strong>短暂(Transient)</strong></li>
<li><strong>持久(Persistent)</strong></li>
<li><strong>Removed</strong></li>
<li><strong>Detached</strong></li>
</ul>
<p>以上几个状态在下面图中解释：</p>
<p><img src="http://www.yiibai.com/uploads/images/201705/0905/689170557_42799.png" alt="img"></p>
<p>下面来看这几个状态的流转说明 -</p>
<ul>
<li>当从一个实体创建一个新的java对象时，该对象处于”短暂”状态，Hibernate不知道它的存在，因为它独立于Hibernate的管理</li>
<li>如果使用方法:<code>get</code> <code>load</code>或者<code>find</code>获取对象实体，则将获取一个等同于数据库中的1条记录的对象，此对象处于Persistent状态，它由Hibernate管理。</li>
<li>会话使用方法：<code>save</code>，<code>saveOrUpdate</code>和<code>persist</code>。 合并将短暂(Transient)对象置于Hibernate的管理之下，此对象转为持久化(<strong>Persistent</strong>)状态。 在使用的具体情况下，它向数据库插入或更新数据。 </li>
<li><code>Session</code>调用<code>evict(..)</code>或<code>clear()</code>，以便从处于Hibernate管理状态的对象处于关闭状态，并且这些对象处于分离(<code>Detached</code>)的状态。 </li>
<li>使用<code>update(..)</code>，<code>saveOrUpdate(..)</code>，<code>merge(..)</code>将有助于重新连接分离对象。 在具体情况下，它会向数据库中创建更新或插入数据。 对象转回持久化(Persistent)状态。 </li>
<li><code>Session</code>调用方法：<code>remove(..)</code>，<code>delete(..)</code>删除除记录并持久化对象 </li>
</ul>
<h2 id="5-用Hibernate插入，更新，删除"><a href="#5-用Hibernate插入，更新，删除" class="headerlink" title="5.用Hibernate插入，更新，删除"></a>5.用Hibernate插入，更新，删除</h2><h4 id="5-1-持久化-Persistent"><a href="#5-1-持久化-Persistent" class="headerlink" title="5.1 持久化(Persistent)"></a>5.1 持久化(Persistent)</h4><p>当一个对像使用 <code>Session</code> 的<code>get()</code>,<code>load()</code>,<code>find()</code>方法获取关联数据时，它处于持久化(Persistent)状态。 </p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/538100537_54337.png" alt="2"></p>
<p>代码示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">    public void testPersistentDemo()&#123;</span><br><span class="line">        Department department = null;</span><br><span class="line">        System.out.println(&quot;- Finding Department deptNo = D10...&quot;);</span><br><span class="line"></span><br><span class="line">        // Persistent object.</span><br><span class="line">        department = DataUtils.findDepartment(session, &quot;D10&quot;);</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- First change Location&quot;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        // Changing something on Persistent object.</span><br><span class="line">        department.setLocation(&quot;Chicago &quot; + System.currentTimeMillis());</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- Location = &quot; + department.getLocation());</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- Calling flush...&quot;);</span><br><span class="line"></span><br><span class="line">        // Use session.flush () to actively push the changes to the DB.</span><br><span class="line">        // It works for all changed Persistent objects.</span><br><span class="line">        session.flush();</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- Flush OK&quot;);</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- Second change Location&quot;);</span><br><span class="line"></span><br><span class="line">        // Change something on Persistent object</span><br><span class="line">        department.setLocation(&quot;Chicago &quot; + System.currentTimeMillis());</span><br><span class="line"></span><br><span class="line">        // Print out location</span><br><span class="line">        System.out.println(&quot;- Location = &quot; + department.getLocation());</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- Calling commit...&quot;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;- Commit OK&quot;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>执行上面代码，得到以下结果 - </p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/839140534_80005%20%281%29.png" alt="2"></p>
<h4 id="5-2瞬态转为持久化状态"><a href="#5-2瞬态转为持久化状态" class="headerlink" title="5.2瞬态转为持久化状态"></a>5.2瞬态转为持久化状态</h4><p><img src="http://p1aoqp63y.bkt.clouddn.com/001.png" alt="2"></p>
<h5 id="瞬态转为持久化状态：使用persist-Object"><a href="#瞬态转为持久化状态：使用persist-Object" class="headerlink" title="瞬态转为持久化状态：使用persist(Object)"></a>瞬态转为持久化状态：使用persist(Object)</h5><p><img src="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180802195211.png" alt="2"></p>
<h5 id="瞬态转为持久化状态：使用save-Object"><a href="#瞬态转为持久化状态：使用save-Object" class="headerlink" title="瞬态转为持久化状态：使用save(Object)"></a>瞬态转为持久化状态：使用save(Object)</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line">@Before</span><br><span class="line">   public void before()&#123;</span><br><span class="line">       sessionFactory=HibernateUtils.getSessionFactory();</span><br><span class="line">       session = sessionFactory.getCurrentSession();</span><br><span class="line"></span><br><span class="line">       // All the action with DB via Hibernate</span><br><span class="line">       // must be located in one transaction.</span><br><span class="line">       // Start Transaction.</span><br><span class="line">       session.getTransaction().begin();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   @After</span><br><span class="line">   public void after()&#123;</span><br><span class="line">       // Commit data.</span><br><span class="line">       session.getTransaction().commit();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   private static DateFormat df = new SimpleDateFormat(&quot;dd-MM-yyyy HH:mm:ss&quot;);</span><br><span class="line"></span><br><span class="line">   private static void persist_Transient(Session session, Employee emp) &#123;</span><br><span class="line"></span><br><span class="line">       // See configuration of timekeeperId:</span><br><span class="line">       // @GeneratedValue(generator = &quot;uuid&quot;)</span><br><span class="line">       // @GenericGenerator(name = &quot;uuid&quot;, strategy = &quot;uuid2&quot;)</span><br><span class="line">       // Create an Object, Transitent state.</span><br><span class="line">       Timekeeper tk2 = new Timekeeper();</span><br><span class="line"></span><br><span class="line">       tk2.setEmployee(emp);</span><br><span class="line">       tk2.setInOut(Timekeeper.IN);</span><br><span class="line">       tk2.setDateTime(new Date());</span><br><span class="line"></span><br><span class="line">       // Now &apos;tk3&apos; are state Transient.</span><br><span class="line">       System.out.println(&quot;- tk2 Persistent? &quot; + session.contains(tk2));</span><br><span class="line"></span><br><span class="line">       System.out.println(&quot;====== CALL save(tk).... ===========&quot;);</span><br><span class="line"></span><br><span class="line">       // save() very similar to persist()</span><br><span class="line">       // save() return ID, persist() return void.</span><br><span class="line">       // Hibernate assign ID value to &apos;tk2&apos;, no action with DB</span><br><span class="line">       // And return ID of &apos;tk2&apos;.</span><br><span class="line">       Serializable id = session.save(tk2);</span><br><span class="line"></span><br><span class="line">       System.out.println(&quot;- id = &quot; + id);</span><br><span class="line"></span><br><span class="line">       //</span><br><span class="line">       System.out</span><br><span class="line">               .println(&quot;- tk2.getTimekeeperId() = &quot; + tk2.getTimekeeperId());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">       // Now, &apos;tk2&apos; has Persistent state</span><br><span class="line">       // It has been managed in Session.</span><br><span class="line">       // ==&gt; true</span><br><span class="line">       System.out.println(&quot;- tk2 Persistent? &quot; + session.contains(tk2));</span><br><span class="line"></span><br><span class="line">       System.out.println(&quot;- Call flush..&quot;);</span><br><span class="line"></span><br><span class="line">       // To push data into the DB, call flush().</span><br><span class="line">       // If not call flush() data will be pushed to the DB when calling commit().</span><br><span class="line">       // Will execute insert statement.</span><br><span class="line">       session.flush();</span><br><span class="line"></span><br><span class="line">       String timekeeperId = tk2.getTimekeeperId();</span><br><span class="line">       System.out.println(&quot;- timekeeperId = &quot; + timekeeperId);</span><br><span class="line">       System.out.println(&quot;- inOut = &quot; + tk2.getInOut());</span><br><span class="line">       System.out.println(&quot;- dateTime = &quot; + df.format(tk2.getDateTime()));</span><br><span class="line">       System.out.println();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   @Test</span><br><span class="line">   public void testSaveTransientDemo()&#123;</span><br><span class="line">       Employee emp = null;</span><br><span class="line">       try &#123;</span><br><span class="line"></span><br><span class="line">           emp = DataUtils.findEmployee(session, &quot;E7499&quot;);</span><br><span class="line">           persist_Transient(session, emp);</span><br><span class="line"></span><br><span class="line">       &#125; catch (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">           session.getTransaction().rollback();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180802202703.png" alt="1"></p>
<h5 id="瞬态转为持久化状态：使用merge-Object"><a href="#瞬态转为持久化状态：使用merge-Object" class="headerlink" title="瞬态转为持久化状态：使用merge(Object)"></a>瞬态转为持久化状态：使用merge(Object)</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"> private static DateFormat df = new SimpleDateFormat(&quot;dd-MM-yyyy HH:mm:ss&quot;);</span><br><span class="line"></span><br><span class="line">  private static Timekeeper saveOrUpdate_Transient(Session session,</span><br><span class="line">          Employee emp) &#123;</span><br><span class="line"></span><br><span class="line">      // Note:</span><br><span class="line">      // Configuring of timekeeperId</span><br><span class="line">      // @GeneratedValue(generator = &quot;uuid&quot;)</span><br><span class="line">      // @GenericGenerator(name = &quot;uuid&quot;, strategy = &quot;uuid2&quot;)        </span><br><span class="line">      Timekeeper tk4 = new Timekeeper();</span><br><span class="line"></span><br><span class="line">      tk4.setEmployee(emp);</span><br><span class="line">      tk4.setInOut(Timekeeper.IN);</span><br><span class="line">      tk4.setDateTime(new Date());</span><br><span class="line"></span><br><span class="line">      // Now &apos;tk4&apos; Transient status.</span><br><span class="line">      System.out.println(&quot;- tk4 Persistent? &quot; + session.contains(tk4));</span><br><span class="line"></span><br><span class="line">      System.out.println(&quot;====== CALL merge(tk).... ===========&quot;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      // Hibernate2 has method saveOrUpdateCopy</span><br><span class="line">      // Hibernate3 change saveOrUpdateCopy to merge</span><br><span class="line">      // So there will be similarities between the two methods merge and copyOrUpdate</span><br><span class="line">      // Here Hibernate check tk4 has ID or not</span><br><span class="line">      // If not, Hibernate assign value to ID of tk4</span><br><span class="line">      // Return copy of tk4.</span><br><span class="line">      Timekeeper tk4Copy = (Timekeeper) session.merge(tk4);</span><br><span class="line"></span><br><span class="line">      System.out</span><br><span class="line">              .println(&quot;- tk4.getTimekeeperId() = &quot; + tk4.getTimekeeperId());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      // Now &apos;tk4&apos; still Transient state.</span><br><span class="line">      // and &apos;tk4Copy&apos; has Persistent status</span><br><span class="line">      // No action with DB (insert or update).</span><br><span class="line">      System.out.println(&quot;- tk4 Persistent? &quot; + session.contains(tk4));</span><br><span class="line"></span><br><span class="line">      // &apos;tk4Copy&apos; has Persistent status</span><br><span class="line">      // ==&gt; true</span><br><span class="line">      System.out</span><br><span class="line">              .println(&quot;- tk4Copy Persistent? &quot; + session.contains(tk4Copy));</span><br><span class="line"></span><br><span class="line">      System.out.println(&quot;- Call flush..&quot;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      // This time have Insert or Update to DB. (!!!)</span><br><span class="line">      session.flush();</span><br><span class="line"></span><br><span class="line">      // &apos;tk4&apos; still Transitent, after flush().</span><br><span class="line">      // merge(..) safer than saveOrUpdate().</span><br><span class="line">      System.out.println(&quot;- tk4 Persistent? &quot; + session.contains(tk4));</span><br><span class="line"></span><br><span class="line">      //</span><br><span class="line">      String timekeeperId = tk4.getTimekeeperId();</span><br><span class="line">      System.out.println(&quot;- timekeeperId = &quot; + timekeeperId);</span><br><span class="line">      System.out.println(&quot;- inOut = &quot; + tk4.getInOut());</span><br><span class="line">      System.out.println(&quot;- dateTime = &quot; + df.format(tk4.getDateTime()));</span><br><span class="line">      System.out.println();</span><br><span class="line">      return tk4;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@Test</span><br><span class="line">   public void testMergeDemo()&#123;</span><br><span class="line">       Employee emp;</span><br><span class="line">       emp = DataUtils.findEmployee(session, &quot;E7499&quot;);</span><br><span class="line">       saveOrUpdate_Transient(session, emp);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h3 id="持久化转变为分离状态"><a href="#持久化转变为分离状态" class="headerlink" title="持久化转变为分离状态"></a>持久化转变为分离状态</h3><p>由Hibernate管理的持久化(Persistent)条件中的一个对象可以通过以下两个<code>Session</code>的方法转换为<code>Detached</code>(独立于Hibernate的管理)状态：</p>
<ul>
<li><code>evict (Object)</code> - 从Hibernate管理中删除一个对象</li>
<li><code>clear()</code> - 从Hibernate管理的对象中删除所有对象。</li>
</ul>
<p>当然，当<code>Session</code>调用顺序为：<code>commit()</code>，<code>close()</code>或<code>rollback()</code>时，当前会话已经完成。 此会话的所有<code>Persistence</code>对象将从新打开的会话中分离。</p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/892100550_69590.png" alt="1"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">package com.anlu.hibenrate.test;</span><br><span class="line"></span><br><span class="line">import com.anlu.hibernate.entity.Employee;</span><br><span class="line">import com.anlu.hibernate.utils.DataUtils;</span><br><span class="line">import com.anlu.hibernate.utils.HibernateUtils;</span><br><span class="line">import org.hibernate.Session;</span><br><span class="line">import org.hibernate.SessionFactory;</span><br><span class="line">import org.junit.After;</span><br><span class="line">import org.junit.Before;</span><br><span class="line">import org.junit.Test;</span><br><span class="line"></span><br><span class="line">import static org.junit.Assert.assertEquals;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 测试从持久化状态到分离状态</span><br><span class="line"> */</span><br><span class="line">public class TestEvict &#123;</span><br><span class="line"></span><br><span class="line">    private SessionFactory sessionFactory;</span><br><span class="line">    private Session session ;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    @Before</span><br><span class="line">    public void before()&#123;</span><br><span class="line">        sessionFactory=HibernateUtils.getSessionFactory();</span><br><span class="line">        session = sessionFactory.getCurrentSession();</span><br><span class="line"></span><br><span class="line">        // All the action with DB via Hibernate</span><br><span class="line">        // must be located in one transaction.</span><br><span class="line">        // Start Transaction.</span><br><span class="line">        session.getTransaction().begin();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @After</span><br><span class="line">    public void after()&#123;</span><br><span class="line">        // Commit data.</span><br><span class="line">        session.getTransaction().commit();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    @Test</span><br><span class="line">    public void testEvic()&#123;</span><br><span class="line"></span><br><span class="line">        Employee emp = null;</span><br><span class="line">        // This is object has Persistent status</span><br><span class="line">        emp = DataUtils.findEmployee(session, &quot;E7499&quot;);</span><br><span class="line"></span><br><span class="line">        // ==&gt; true</span><br><span class="line">        System.out.println(&quot;- emp Persistent? &quot; + session.contains(emp));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        // using evict() to evicts a single object from the session</span><br><span class="line">        session.evict(emp);</span><br><span class="line"></span><br><span class="line">        // Now &apos;emp&apos; has Detached status</span><br><span class="line">        // ==&gt; false</span><br><span class="line">        System.out.println(&quot;- emp Persistent? &quot; + session.contains(emp));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        // All change on the &apos;emp&apos; will not update</span><br><span class="line">        // if not reatach &apos;emp&apos; to session</span><br><span class="line">        emp.setEmpNo(&quot;NEW&quot;);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180803114430.png" alt="1"></p>
<h3 id="分离状态转变为持久化状态"><a href="#分离状态转变为持久化状态" class="headerlink" title="分离状态转变为持久化状态"></a>分离状态转变为持久化状态</h3><p>Hibernate管理分离的对象可以通过以下<code>Session</code>的一些方法重新附加：</p>
<ul>
<li>update(Object)</li>
<li>saveOrUpdate(Object)</li>
<li>merge(Object)</li>
<li>refresh(Object)</li>
<li>lock(Object)</li>
</ul>
<p>可以在以下示例中看到这些方法的区别：</p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/721100554_22650.png" alt="2"></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-07-31-Hibernate的基本用法/" data-id="cjoztxu79002y1wijwb4qwco2" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-06-18-SpringBoot整合Mybatis/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          springboot整合Mybatis
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2017-12-04-Spring-secrity-role-basedLogin/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Spring-secrity-role-basedLogin</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>